﻿CREATE FUNCTION dbo.sf_GetPreviousMonthOrYear
(
	@Year int, 
	@Month int,
	@Offset int,
	@Type int
)
RETURNS INT
AS
BEGIN
declare @Result int
	if @Type = 0
		set @Result = month(dateadd(month, @Offset, cast(cast(@year AS Varchar(4)) + case when len(@month) =1 then '0' else '' end + cast(@month AS nvarchar(2)) +'01' as Datetime)))
	else
		set @Result = year(dateadd(month, @Offset, cast(cast(@year AS Varchar(4)) + case when len(@month) =1 then '0' else '' end + cast(@month AS nvarchar(2)) +'01' as Datetime)))
	
	return @Result
END